#include "ordermanager.h"
#include "ui_ordermanager.h"
#include "orderstatuswidget.h"
#include "paymentwidget.h"
#include "DatabaseManager.h"
#include "commentwidget.h"
#include "mainwindow.h"
#include <QtSql>
#include <QSqlDatabase>
#include <QDebug>
#include <QString>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <QDir>
#include <QCoreApplication>
#include <QSqlQuery>
#include <QSqlQueryModel>
#include <QSqlTableModel>
#include <QLineEdit>
#include<QVBoxLayout>
#include<QVector>
#include<QStandardItemModel>
#include<QHash>

orderManager::orderManager(QWidget *parent, int userId) :
    QDialog(parent),
    ui(new Ui::orderManager),
    m_currentUserId(userId)
{
    ui->setupUi(this);

    db = DatabaseManager::instance().database();
    if (!db.isOpen()) {
            QMessageBox::critical(this, "错误", "数据库连接未打开");
        }
    // 设置主窗口
    setWindowTitle("订单管理系统");
    resize(800, 600);
    // 设置当前用户ID (实际应用中应从登录信息获取)
    //m_currentUserId = 2; // 测试用，实际应从登录信息获取
    // 初始化 orderStatusWidget
       orderSW = new orderStatusWidget(this);
       //orderSW->hide(); // 初始时隐藏


       // 加载当前用户的订单
       loadOrderHistory(m_currentUserId);

       // 连接信号槽
      // 表格选择变化时更新当前选中的订单ID
       connect(ui->ordersTableView->selectionModel(), &QItemSelectionModel::selectionChanged,
               this, &orderManager::onTableSelectionChanged);
       // 设置表格样式 - 使用Qt 5.3支持的样式表
           ui->ordersTableView->setStyleSheet(
               "QTableView {"
               "   background-color: #f8f9fa;"
               "   alternate-background-color: #e9ecef;"
               "   gridline-color: #dee2e6;"
               "}"
               "QHeaderView::section {"
               "   background-color: #e0e0e0;"
               "   padding: 4px;"
               "   border: 1px solid #dee2e6;"
               "   font-weight: bold;"
               "}"
               "QTableView::item:selected {"
               "   background-color: #b3d7ff;"
               "   color: #000000;"
               "}"
           );

}

orderManager::~orderManager()
{
    delete ui;
}


//加载指定用户的订单历史
void orderManager::loadOrderHistory(int userId)
{
    qDebug() << "Loading order history for user ID:" << userId;
    // 获取订单列表
    QVector<OrderSummary> orders = fetchOrderList(userId);
    qDebug() << "Fetched" << orders.size() << "orders";
    // 检查是否获取到数据
    if (orders.isEmpty()) {
        QSqlError error = db.lastError();
        if (error.isValid()) {
            qDebug() << "Database error:" << error.text();
            QMessageBox::warning(this, "数据库错误", "查询订单失败: " + error.text());
        } else {
            QMessageBox::information(this, "提示", "您还没有任何订单");
        }

        // 创建空模型并设置表头
        QStandardItemModel *model = new QStandardItemModel(this);
        model->setHorizontalHeaderLabels({"订单号", "总金额", "下单时间", "状态"});
        ui->ordersTableView->setModel(model);
        return;
    }

    // 创建模型
    QStandardItemModel *model = new QStandardItemModel(orders.size(), 4, this); // 明确指定行数和列数

    // 设置表头
    model->setHorizontalHeaderLabels({"订单号", "总金额", "下单时间", "状态"});

    // 填充数据
    for (int i = 0; i < orders.size(); ++i) {
        const OrderSummary &order = orders[i];

        // 订单号
        QStandardItem *idItem = new QStandardItem(QString::number(order.orderId));
        idItem->setTextAlignment(Qt::AlignCenter);
        model->setItem(i, 0, idItem);

        // 总金额
        QStandardItem *priceItem = new QStandardItem(QString::number(order.totalPrice, 'f', 2));
        priceItem->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter);
        model->setItem(i, 1, priceItem);

        // 下单时间
        QStandardItem *timeItem = new QStandardItem(order.createTime.toString("yyyy-MM-dd hh:mm"));
        timeItem->setTextAlignment(Qt::AlignCenter);
        model->setItem(i, 2, timeItem);

        // 状态
        QStandardItem *statusItem = new QStandardItem(order.status);
        statusItem->setTextAlignment(Qt::AlignCenter);

        // 根据状态设置文本颜色
        if (order.status == "待支付") {
            statusItem->setForeground(QBrush(Qt::red));
        } else if (order.status == "已支付") {
            statusItem->setForeground(QBrush(Qt::darkGreen));
        } else if (order.status == "已完成") {
            statusItem->setForeground(QBrush(Qt::blue));
        }
        model->setItem(i, 3, statusItem);
    }


    // 在填充数据后添加调试
        qDebug() << "加载的订单:";
        for (const OrderSummary &order : orders) {
            qDebug() << " - 订单ID:" << order.orderId
                     << "用户ID:" << userId
                     << "状态:" << order.status;
        }

    // 设置表格视图
    ui->ordersTableView->setModel(model);

    // 设置表格属性
    ui->ordersTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->ordersTableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->ordersTableView->setEditTriggers(QAbstractItemView::NoEditTriggers); // 禁止编辑

    // 调整列宽
    ui->ordersTableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); // 订单号自适应
    ui->ordersTableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);         // 金额自适应
    ui->ordersTableView->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); // 时间自适应
    ui->ordersTableView->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Fixed);           // 固定状态列宽
    ui->ordersTableView->setColumnWidth(3, 100); // 设置状态列宽

    // 添加样式
    ui->ordersTableView->setStyleSheet(
        "QTableView {"
        "   background-color: #f8f9fa;"
        "   alternate-background-color: #e9ecef;"
        "   gridline-color: #dee2e6;"
        "}"
        "QHeaderView::section {"
        "   background-color: #e0e0e0;"
        "   padding: 4px;"
        "   border: 1px solid #dee2e6;"
        "   font-weight: bold;"
        "}"
    );

    // 确保表格刷新显示
    ui->ordersTableView->update();
    ui->ordersTableView->repaint();
    qDebug() << "执行力loadOrderHistory方法";
}

// 获取指定用户的订单列表（该用户所有订单）
QVector<OrderSummary> orderManager::fetchOrderList(int userId)
{
    QVector<OrderSummary> orders;
    QSqlQuery query(db);
       QString sql =
           "SELECT order_id, total_price, create_time, status "
           "FROM Orders "
           "WHERE user_id = :user_id "  // 使用命名参数
           "ORDER BY create_time DESC";

       query.prepare(sql);
       query.bindValue(":user_id", userId);  // 使用命名参数绑定

    if (query.exec()) {
            while (query.next()) {
                OrderSummary summary;
                summary.orderId = query.value("order_id").toInt();
                summary.totalPrice = query.value("total_price").toDouble();
                summary.createTime = query.value("create_time").toDateTime();
                summary.status = query.value("status").toString();
                orders.append(summary);
            }
            qDebug() << "获取到" << orders.size() << "条订单记录1111";
        } else {
            qWarning() << "订单列表查询失败:" << query.lastError().text();
            qWarning() << "实际执行SQL:" << query.executedQuery();

            // 检查表结构 - 修正后的代码
                    QSqlRecord record = db.record("Orders");
                    QStringList fieldNames;
                    for (int i = 0; i < record.count(); ++i) {
                        fieldNames.append(record.fieldName(i));
                    }
                    qDebug() << "Orders表字段:" << fieldNames;
        }
    qDebug() << "执行了fetchOrderList方法";
    return orders;
}

// 从订单历史中选择订单，表格选择变化时的处理
void orderManager::onTableSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
    Q_UNUSED(deselected);

    if (selected.isEmpty()) {
        m_currentOrderId = -1;
        return;
    }

    // 获取选中的行
    int row = selected.indexes().first().row();

    // 获取订单ID（第一列）
    QModelIndex index = ui->ordersTableView->model()->index(row, 0);
    m_currentOrderId = ui->ordersTableView->model()->data(index).toInt();

    qDebug() << "Selected order ID:" << m_currentOrderId;
    qDebug() << "执行了onTableSelectionChanged方法";
}

//显示指定订单的详细信息
void orderManager::showOrderDetails(int orderId)
{
    // 从数据库获取订单数据
    OrderDetail orderDetail = fetchOrderDetails(orderId);

    // 创建订单详情对话框
    orderStatusWidget *orderDialog = new orderStatusWidget(this);

    // 设置订单基本信息
    orderDialog->setOrderInfo(
        QString::number(orderDetail.orderId),
        orderDetail.createTime,
        orderDetail.status,
        "微信支付" // 支付方式需要从订单表添加
    );

    // 添加商品 - 使用 addProduct 函数
    for (const auto &product : orderDetail.products) {
        orderDialog->addProduct(
            product.name,
            product.imagePath, // 使用实际图片路径
            product.price,
            product.quantity
        );
    }

    // 设置收货信息
    orderDialog->setShippingInfo(
        orderDetail.user.username,
        orderDetail.user.phone,
        orderDetail.address,
        "顺丰快递", // 物流公司需要添加到Orders表
        "SF" + QString::number(orderDetail.orderId)// 物流单号需要添加到Orders表
    );

    // 计算实际支付金额
    double subtotal = 0.0;
    if (!orderDetail.products.isEmpty()) {
        for (const auto &product : orderDetail.products) {
            subtotal += product.price * product.quantity;
        }
    } else {
        qWarning() << "No products found for order, using total price directly";
        subtotal = orderDetail.totalPrice.toDouble();
    }
    // 计算运费和折扣（实际应用中应从数据库获取）
        double shippingFee = 15; // 运费
        double discount =0;     // 折扣
        // 计算总价 = 商品小计 + 运费 - 折扣
        double total = subtotal + shippingFee - discount;

    // 设置价格信息
    orderDialog->setPriceInfo(
        subtotal,
        shippingFee, // 运费
        discount,  // 折扣（暂时设为0）
       total
    );

    // 连接信号槽
    connect(orderDialog, &orderStatusWidget::paymentRequested, [this](const QString &id) {
        processPayment(id.toInt());
    });

    // 显示对话框
    orderDialog->exec();
    delete orderDialog; // 防止内存泄漏
    qDebug() << "执行了showOrderDetails方法";
}

//从数据库读取数据并赋值给结构体
OrderDetail orderManager::fetchOrderDetails(int orderId)
{
    OrderDetail detail;
    QSqlQuery orderQuery(db);

    // 根据实际表结构查询订单信息
    QString orderSql = QString(
        "SELECT o.order_id, o.user_id, o.total_price, o.create_time, "
        "o.status, o.address, u.phone,u.username "  // 从login_users表获取username
        "FROM Orders o "
        "JOIN login_users u ON o.user_id = u.user_id "
        "WHERE o.order_id = %1").arg(orderId);

    if (orderQuery.exec(orderSql) && orderQuery.next()) {
        detail.orderId = orderQuery.value("order_id").toInt();
        detail.userId = orderQuery.value("user_id").toInt();
        detail.totalPrice = orderQuery.value("total_price").toString();
        detail.createTime = orderQuery.value("create_time").toDateTime();
        detail.status = orderQuery.value("status").toString();
        detail.address = orderQuery.value("address").toString();
        detail.user.username = orderQuery.value("username").toString();
        detail.user.phone = orderQuery.value("phone").toString();// 使用username
    }

    // 查询订单商品
    QSqlQuery productsQuery(db);
    productsQuery.prepare(
        "SELECT p.product_id, p.name, p.price, p.image_path, od.quantity "
        "FROM OrderDetails od "
        "JOIN products p ON od.product_id = p.product_id "
        "WHERE od.order_id = ?");
    productsQuery.addBindValue(orderId);

    if (productsQuery.exec()) {
        while (productsQuery.next()) {
            OrderDetail::ProductItem item;
            item.productId = productsQuery.value("product_id").toInt();
            item.name = productsQuery.value("name").toString();
            item.price = productsQuery.value("price").toDouble();
            item.imagePath = productsQuery.value("image_path").toString();
            item.quantity = productsQuery.value("quantity").toInt();
            detail.products.append(item);
        }
    }

    return detail;
}

//从数据库中获得指定订单的商品信息并返回
void orderManager::fetchOrderProducts(int orderId, QVector<ProductDetail> &products)
{
    QSqlQuery query(db);
    query.prepare(
        "SELECT p.product_id, p.name, p.price, oi.quantity, p.image_path "
        "FROM OrderDetails oi "
        "JOIN products p ON oi.product_id = p.product_id "
        "WHERE oi.order_id = :order_id"
    );
    query.bindValue(":order_id", orderId);

    if (query.exec()) {
        while (query.next()) {
            ProductDetail product;
            product.productId = query.value("product_id").toInt();
            product.name = query.value("name").toString();
            product.price = query.value("price").toDouble();
            product.quantity = query.value("quantity").toInt();
            product.imagePath = query.value("image_path").toString();
            products.append(product);
        }
    } else {
        qWarning() << "Failed to fetch order products:" << query.lastError().text();
    }
    qDebug() << "执行了fetchOrderProducts(orderId,products)方法";
}

//点击查看订单详情（调用showOrderDetails）
void orderManager::on_showOrderButton_clicked()
{
    qDebug() << "尝试查看订单 ID:" << m_currentOrderId;
    if (m_currentOrderId <= 0) {
            QMessageBox::warning(this, "提示", "请先在表格中选择一个订单");
            return;
        }
        showOrderDetails(m_currentOrderId);
        qDebug() << "执行了on_showOrderButton_clicked方法";
}


//点击支付时跳转支付界面
void orderManager::processPayment(int orderId)
{
    // 实现支付处理逻辑
    // 例如：更新数据库、发送支付请求等
//    PaymentWidget* pay=new PaymentWidget();
//    pay->setAttribute(Qt::WA_DeleteOnClose);
//        pay->show();
        //this->hide();
    qDebug() << "processPayment";
}

//点击商品评价
void orderManager::on_commentButton_clicked()
{
    commentWidget * CW = new commentWidget(m_currentUserId, this);
        CW->setAttribute(Qt::WA_DeleteOnClose);
        CW->show();
        qDebug() << "执行了on_commentButton_clicked方法";
}
